package com.example.demo.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.dao.SaveCCMapper;
import com.example.demo.entity.PictureCc;
import com.example.demo.entity.SaveCC;
import com.example.demo.entity.VideoCc;
import com.example.demo.entity.VoiceCc;
import com.example.demo.service.PictureCcService;
import com.example.demo.service.SaveCCService;
import com.example.demo.service.VideoCcService;
import com.example.demo.service.VoiceCcService;
import com.example.demo.util.CosUtil;
import com.example.demo.vo.DataView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import static com.example.demo.util.CosUtil.uploadResource;

@Service
@Slf4j
public class DraftsReceiverServiceImpl extends ServiceImpl<SaveCCMapper, SaveCC> implements SaveCCService {


    @Value("${drafts.voices}")
    private String voicePath;

    @Value("${drafts.videos}")
    private String videoPath;

    @Value("${drafts.images}")
    private String imagesPath;

    @Value("${cos.secretId}")
    private String secretId;
    @Value("${cos.secretKey}")
    private String secretKey;
    @Value("${cos.regionName}")
    private String regionName;
    @Value("${cos.bucketName}")
    private String bucketName;

    @Autowired
    private VideoCcService videoCcService;

    @Autowired
    private PictureCcService pictureCcService;

    @Autowired
    private VoiceCcService voiceCcService;

    private final static ExecutorService executorService = Executors.newFixedThreadPool(3);

    @Override
    public DataView receiveVideos(MultipartFile[] videoFiles, HttpServletRequest request) throws IOException {
        DataView dataView = new DataView();
        String openid = request.getHeader("openid");
        if(null == openid)
        {
            dataView.setCode(300);
            dataView.setMsg("用户没有登录");
            return dataView;
        }
        if(videoFiles == null)
        {
            dataView.setCode(200);
            dataView.setMsg("");
            return dataView;
        }

        Runnable task= ()->{
            try {
                saveVideo(videoFiles,openid);
            } catch (IOException e) {
                log.error("保存视频发生错误。{}",e.getMessage());
                e.printStackTrace();
            }
        };

        saveVideo(videoFiles,openid);
        //executorService.submit(task);
        dataView.setCode(200);
        dataView.setMsg("视频上传成功");
        return dataView;
    }

    /**
     * 开一个单独的线程来实现视频的保存
     * @param videoFiles
     * @param openid
     */
    private void saveVideo(MultipartFile[] videoFiles,String openid) throws IOException {
        //List<VideoCc> list = videoCcService.query().eq("wechat_openid", openid).list();

        QueryWrapper<VideoCc> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wechat_openid",openid);
        videoCcService.remove(queryWrapper);

        List<VideoCc> videoCcs = new ArrayList<>();


        for(MultipartFile multipartFile : videoFiles)
        {
            String originalFilename = multipartFile.getOriginalFilename();

            String pathFile = videoPath+openid+"/"+originalFilename;

            String path = uploadResource(multipartFile, pathFile);

            VideoCc videoCc = new VideoCc();
            videoCc.setVideoPath(path);
            videoCc.setWechatOpenid(openid);
            videoCcs.add(videoCc);
        }


        videoCcService.saveBatch(videoCcs);

    }

    /**
     * 接收图片
     */

    @Override
    public DataView receivePictures(MultipartFile[] images, HttpServletRequest request) throws IOException {
        DataView dataView = new DataView();
        String openid = request.getHeader("openid");
        if(openid == null)
        {
            dataView.setCode(300);
            dataView.setMsg("用户没有登录");
            return dataView;
        }

        Runnable task = ()->{
            try {
                savePicture(images,openid);
            } catch (IOException e) {
                log.error("保存图片发生错误。{}",e.getMessage());
                e.printStackTrace();
            }
        };

        //executorService.submit(task);

        savePicture(images,openid);

        dataView.setCode(200);
        dataView.setMsg("图片上传成功");
        return dataView;
    }



    private void savePicture(MultipartFile[] images ,String openid) throws IOException {

        //List<PictureCc> list = pictureCcService.query().eq("wechat_openid", openid).list();

        QueryWrapper<PictureCc> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wechat_openid",openid);
        pictureCcService.remove(queryWrapper);

        List<PictureCc> pictureCcs = new ArrayList<>();


        for (MultipartFile multipartFile:images) {

            String originalFilename = multipartFile.getOriginalFilename();

            String pathFile = imagesPath+openid+"/"+originalFilename;

            String path = uploadResource(multipartFile, pathFile);

            PictureCc pictureCc = new PictureCc();
            pictureCc.setPicturePath(path);
            pictureCc.setWechatOpenid(openid);
            pictureCcs.add(pictureCc);

        }
        pictureCcService.saveBatch(pictureCcs);
    }

    @Override
    public DataView receiveVoice(MultipartFile voiceFile, HttpServletRequest request) throws IOException {

        String openid = request.getHeader("openid");
        DataView dataView = new DataView();
        if(null == openid)
        {
            dataView.setCode(300);
            dataView.setMsg("用户未登录");
            return dataView;
        }
        if(voiceFile == null || voiceFile.isEmpty())
        {
            dataView.setCode(300);
            dataView.setMsg("数据为空");
            return dataView;
        }

        QueryWrapper<VoiceCc> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wechat_openid",openid);
        voiceCcService.remove(queryWrapper);



        String pathFile = voicePath+openid+"/"+voiceFile.getOriginalFilename();

        String path = uploadResource(voiceFile, pathFile);

        VoiceCc voiceCc = new VoiceCc();
        voiceCc.setVoicePath(path);
        voiceCc.setWechatOpenid(openid);
        voiceCcService.save(voiceCc);

        dataView.setMsg("上传成功");
        dataView.setCode(200);
        return dataView;
    }



    @Override
    public DataView sendVideo(HttpServletRequest request) {
        DataView dataView = new DataView();

        String openid = request.getHeader("openid");
        if (openid == null) {
            dataView.setCode(300);
            dataView.setMsg("用户未登录");
            return dataView;
        }

        List<VideoCc> videoCcs = videoCcService.query().eq("wechat_openid", openid).list();

        dataView.setCode(200);
        dataView.setData(videoCcs);
        return dataView;
    }

    @Override
    public DataView sendVoice(HttpServletRequest request) {
        DataView dataView = new DataView();

        String openid = request.getHeader("openid");
        if (openid == null) {
            dataView.setCode(300);
            dataView.setMsg("用户未登录");
        }

        List<VoiceCc> voiceCcs = voiceCcService.query().eq("wechat_openid", openid).list();

        dataView.setCode(200);
        dataView.setData(voiceCcs);
        return dataView;
    }

    @Override
    public DataView sendPicture(HttpServletRequest request) {

        DataView dataView = new DataView();

        String openid = request.getHeader("openid");
        if (openid == null) {
            dataView.setCode(300);
            dataView.setMsg("用户未登录");
            return dataView;
        }

        List<PictureCc> pictureCcs = pictureCcService.query().eq("wechat_openid", openid).list();

        dataView.setCode(200);
        dataView.setData(pictureCcs);
        return dataView;
    }

    @Override
    public DataView send(HttpServletRequest request) {

        DataView dataView = new DataView();

        String openid = request.getHeader("openid");
        if(openid == null||openid.equals(""))
        {
            dataView.setMsg("用户未登录");
            dataView.setCode(300);
            return dataView;
        }

      SaveCC saveCCS = this.query().eq("wechat_openid", openid).one();
        if(saveCCS == null)
        {
            return dataView;
        }

        List<PictureCc> pictureCcs = pictureCcService.query().eq("wechat_openid", openid).list();
        List<VideoCc> videoCcs = videoCcService.query().eq("wechat_openid", openid).list();
        VoiceCc voiceCc = voiceCcService.query().eq("wechat_openid", openid).one();
        List<String> picturePaths = pictureCcs.stream().map((pictureCc -> {
            return pictureCc.getPicturePath();
        })).collect(Collectors.toList());
        saveCCS.setPicturePaths(picturePaths);

        List<String> videoPaths = videoCcs.stream().map(videoCc -> {
            return videoCc.getVideoPath();
        }).collect(Collectors.toList());
        saveCCS.setVideoPaths(videoPaths);

        if (voiceCc!=null)
        {
            saveCCS.setVoicePath(voiceCc.getVoicePath());
        }

        dataView.setCode(200);
        dataView.setData(saveCCS);
        return dataView;
    }

    @Override
    public DataView receiveLetter(SaveCC saveCC, HttpServletRequest request) {
        DataView dataView = new DataView();
        String openid = request.getHeader("openid");
        if(openid == null)
        {
            dataView.setCode(300);
            dataView.setMsg("用户未登录");
            return dataView;
        }
        saveCC.setWechatOpenid(openid);
        saveOrUpdate(saveCC);
        dataView.setData(saveCC);
        return dataView;
    }


}
